package com.saianfu.flowable.demo.config

import com.alibaba.druid.pool.DruidDataSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import javax.sql.DataSource

/**
 *
 * @author pei
 * @date 2020-07-22
 */
@Configuration
class DruidConfiguration {

    @Autowired
    private lateinit var env: Environment

    @Bean
    fun dataSource(): DataSource {
        val ds = DruidDataSource()
        ds.url = env.getProperty("spring.datasource.url")
        ds.driverClassName = env.getProperty("spring.datasource.driver-class-name")
        ds.password = env.getProperty("spring.datasource.password")
        ds.username = env.getProperty("spring.datasource.username")
        ds.initialSize = 5//初始化时建立物理连接的个数
        ds.maxActive = 20//最大连接池数量
        ds.minIdle = 2//最小连接池数量
        ds.maxWait = 60000//获取连接时最大等待时间，单位毫秒。
        ds.validationQuery = "SELECT 1 FROM DUAL"//用来检测连接是否有效的sql
        ds.isTestOnBorrow = false//申请连接时执行validationQuery检测连接是否有效
        ds.isTestWhileIdle = true//建议配置为true，不影响性能，并且保证安全性。
        ds.isPoolPreparedStatements = false//是否缓存preparedStatement，也就是PSCache
        return ds
    }


    @Bean("dataSourceTransactionManager")
    fun dataSourceTransactionManager(dataSource: DataSource) = DataSourceTransactionManager(dataSource)
}